package com.zm.shop.listener;


import com.rabbitmq.client.Channel;
import com.zm.shop.common.constants.RabbitMQCons;
import com.zm.shop.common.entity.Email;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.internet.MimeMessage;

@Component
@Slf4j
public class EmailListener {

    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String sender;

    @RabbitListener(queues = RabbitMQCons.EMAIL_QUEUE)
    public void send(Email email, Channel channel, Message message) {

        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();  //创建一个邮件模板对象
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true); //邮件构造器
            helper.setSubject(email.getTitle());    //邮件标题
            helper.setText(email.getContent(), true); //邮件内容
            String[] strArray = {};
            helper.setFrom(sender); // 发件人
            helper.setTo(email.getReceiverList().toArray(strArray)); // 收件人
            javaMailSender.send(mimeMessage); //发送邮件
            //消费Email消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            log.error("发送邮件失败", e);
        }


    }
}
